
clear all
clear mata
clear matrix
set more off
set scheme modern

*set path here*

global rawdata = 
global workingdata = 
global match = 
global temp = 
global table = 


**************************************************************************************
*calculate the number of days falling in each temperature bin during the past 30 days*
**************************************************************************************

use $match\weather.dta, clear

gen tempbin1=(temp<=12) if temp!=.
gen tempbin2=(temp>12&temp<=14) if temp!=.
gen tempbin3=(temp>14&temp<=16) if temp!=.
gen tempbin4=(temp>16&temp<=18) if temp!=.
gen tempbin5=(temp>18&temp<=20) if temp!=.
gen tempbin6=(temp>20&temp<=22) if temp!=.
gen tempbin7=(temp>22&temp<=24) if temp!=.
gen tempbin8=(temp>24&temp<=26) if temp!=.
gen tempbin9=(temp>26&temp<=28) if temp!=.
gen tempbin10=(temp>28&temp<=30) if temp!=.
gen tempbin11=(temp>30&temp<=32) if temp!=.
gen tempbin12=(temp>32) if temp!=.

xtset countyid day

foreach k in 30 {
forvalues p=1/12 {
tssmooth ma tempbin`p'_sum_30=tempbin`p', window(`k' 0 0)
replace tempbin`p'_sum_30=round(tempbin`p'_sum_30*`k')
}
}

*calculate the placebo exposure*
forvalues p=1/12 {
gen tempbin`p'_F1=F1.tempbin`p'
}

drop tempbin1-tempbin12 year

save $match\weather_cumul.dta, replace

***************************************************
*calculate the number of consecutive heatwave days*
***************************************************

use $match\weather.dta, clear

gen tempbin12=(temp>32) if temp!=.

xtset countyid day

*ssc install tsspell
tsspell tempbin12
bys countyid _spell: gen lastcontinueday = sum(tempbin12)  //Number of consecutive heatwave days immediately before the survey

*ssc install rangestat
rangestat (max) last30d=lastcontinueday, interval(day -29 0) by(countyid)  //The longest consecutive heatwave days in the past month

keep countyid day lastcontinueday last30d

save $match\cumulday.dta, replace

